package com.epam.newsmanagement.database.dao.jpa;

import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.epam.newsmanagement.database.dao.INewsDAO;
import com.epam.newsmanagement.database.dao.exception.DAOException;
import com.epam.newsmanagement.model.News;


public final class JPANewsDAO implements INewsDAO {
	private static final String JPQL_READ_ALL = "read_all";
	private static final String JPQL_DELETE = "delete";
	private static final String JPQL_PARAMETER_SELECTED_NEWS = "selectedNews";
	private EntityManagerFactory entityManagerFactory;
	
	@Override
	public void save(News news) throws DAOException {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		try{			
			EntityTransaction entityTransaction = entityManager.getTransaction();
			entityTransaction.begin();
			if(news.getId() != null){
				news = entityManager.merge(news);
			}else {
				entityManager.persist(news);
			}
			entityTransaction.commit();
		} finally {
			entityManager.close();
		}
	}

	@Override
	public List<News> getList() throws DAOException {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		try {
			EntityTransaction entityTransaction = entityManager.getTransaction();
			entityTransaction.begin();
			Query query = entityManager.createNamedQuery(JPQL_READ_ALL);
			@SuppressWarnings("unchecked")
			List <News> list = query.getResultList();
			entityTransaction.commit();
			return list;
		} finally{
			entityManager.close();
		}
	}

	@Override
	public void remove(Integer[] selectedNews) throws DAOException {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		try {
			EntityTransaction entityTransaction = entityManager.getTransaction();
			entityTransaction.begin();
			Query query = entityManager.createNamedQuery(JPQL_DELETE);
			List<Integer> list = Arrays.asList(selectedNews);
			query.setParameter(JPQL_PARAMETER_SELECTED_NEWS, list);
			query.executeUpdate();
			entityTransaction.commit();
		} finally{
			entityManager.close();
		}
	}

	@Override
	public News fetchById(int id) throws DAOException {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		try{			
			EntityTransaction entityTransaction = entityManager.getTransaction();
			entityTransaction.begin();
			News news = entityManager.find(News.class, id);	
			entityTransaction.commit();			
			return news;		
		} finally{
			entityManager.close();
		}
	}

	public EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

	public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}

}
